package online.afeibaili.storebackendframework.other

import online.afeibaili.storebackendframework.af.OrderInterface
import online.afeibaili.storebackendframework.model.OrderEntity
import online.afeibaili.storebackendframework.model.json.ProductJsonMapper
import online.afeibaili.storebackendframework.repository.OrderRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component


/**
 * AfInterface实现类
 *
 *@author AfeiBaili
 *@version 2025/10/20 14:44
 */

@Component
class OrderInterfaceImpl : OrderInterface {
    @Autowired
    lateinit var repository: OrderRepository

    data class ProductObj(val createTime: String, val sales: Int)

    override fun selectStat(beginTime: Long, endTime: Long): List<Any> {
        val entities: List<OrderEntity> = repository.findByCreateTimeBetweenAndPayed(beginTime, endTime)

        val list =
            entities
                .flatMap { orderEntity -> ProductJsonMapper.toListObject(orderEntity.products) }
                .groupBy { it.productId }
                .map { (productId, products) -> ProductObj(productId.toString(), products.sumOf { it.count }) }
                .toList()
        return list
    }
}